using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;

namespace SmartMedical.WinUI
{
    /// <summary>
    /// 门诊收费窗体
    /// </summary>
    public partial class OutpatientChargeForm : Form
    {
        #region 私有字段
        private HttpClient _httpClient;
        private const string API_BASE_URL = "http://localhost:5043"; // Read API地址
        private const string WRITE_API_BASE_URL = "http://localhost:5165"; // Write API地址
        #endregion

        #region 构造函数
        /// <summary>
        /// 初始化门诊收费窗体
        /// </summary>
        public OutpatientChargeForm()
        {
            InitializeComponent();
            InitializeHttpClient();
            InitializeForm();
        }
        #endregion

        #region 初始化方法
        /// <summary>
        /// 初始化HTTP客户端
        /// </summary>
        private void InitializeHttpClient()
        {
            _httpClient = new HttpClient();
            _httpClient.Timeout = TimeSpan.FromSeconds(30);
        }

        /// <summary>
        /// 初始化窗体设置
        /// </summary>
        private void InitializeForm()
        {
            this.Text = "门诊收费";
            this.WindowState = FormWindowState.Maximized;
            this.StartPosition = FormStartPosition.CenterScreen;
            
            // 初始化数据网格视图
            InitializeDataGridViews();
        }

        /// <summary>
        /// 初始化数据网格视图
        /// </summary>
        private void InitializeDataGridViews()
        {
            // 初始化未付费患者列表
            dataGridViewUnpaidPatients.AutoGenerateColumns = false;
            dataGridViewUnpaidPatients.Columns.Clear();
            dataGridViewUnpaidPatients.Columns.Add(new DataGridViewTextBoxColumn
            {
                Name = "RegistrationNumber",
                HeaderText = "挂单号",
                DataPropertyName = "RegistrationNumber",
                Width = 100  // 调整挂单号列宽
            });
            dataGridViewUnpaidPatients.Columns.Add(new DataGridViewTextBoxColumn
            {
                Name = "PatientName",
                HeaderText = "名字",
                DataPropertyName = "Name",
                Width = 80   // 调整姓名列宽
            });
            dataGridViewUnpaidPatients.Columns.Add(new DataGridViewTextBoxColumn
            {
                Name = "Gender",
                HeaderText = "性别",
                DataPropertyName = "Gender",
                Width = 50   // 调整性别列宽
            });
            dataGridViewUnpaidPatients.Columns.Add(new DataGridViewTextBoxColumn
            {
                Name = "Department",
                HeaderText = "科室",
                DataPropertyName = "Department",
                Width = 120  // 调整科室列宽
            });
            dataGridViewUnpaidPatients.Columns.Add(new DataGridViewTextBoxColumn
            {
                Name = "IdCard",
                HeaderText = "身份证",
                DataPropertyName = "IdCard",
                Width = 180  // 调整身份证列宽，适应18位身份证号
            });
            
            // 初始化患者消费明细列表
            dataGridViewPatientDetails.AutoGenerateColumns = false;
            dataGridViewPatientDetails.Columns.Clear();
            dataGridViewPatientDetails.Columns.Add(new DataGridViewTextBoxColumn
            {
                Name = "MedicineName",
                HeaderText = "药品名称",
                DataPropertyName = "MedicineName",
                Width = 250  // 调整药品名称列宽，药品名称通常较长
            });
            dataGridViewPatientDetails.Columns.Add(new DataGridViewTextBoxColumn
            {
                Name = "UnitPrice",
                HeaderText = "药品单价",
                DataPropertyName = "UnitPrice",
                Width = 120, // 调整单价列宽，适应价格显示
                DefaultCellStyle = new DataGridViewCellStyle { Format = "F2" }
            });
            dataGridViewPatientDetails.Columns.Add(new DataGridViewTextBoxColumn
            {
                Name = "Quantity",
                HeaderText = "数量",
                DataPropertyName = "Quantity",
                Width = 80   // 数量列宽保持不变
            });
        }
        #endregion

        #region 事件处理方法
        /// <summary>
        /// 查找按钮点击事件
        /// </summary>
        private void ButtonSearch_Click(object sender, EventArgs e)
        {
            try
            {
                string registrationNumber = textBoxRegistrationNumber.Text.Trim();
                string patientName = textBoxPatientName.Text.Trim();
                string gender = comboBoxGender.SelectedItem?.ToString();

                if (string.IsNullOrEmpty(registrationNumber) && string.IsNullOrEmpty(patientName))
                {
                    MessageBox.Show("请输入挂单号或姓名进行查询", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                SearchPatients(registrationNumber, patientName, gender);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"查询失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 取消按钮点击事件
        /// </summary>
        private void ButtonCancel_Click(object sender, EventArgs e)
        {
            ClearForm();
        }

        /// <summary>
        /// 未付费患者选择变更事件
        /// </summary>
        private void DataGridViewUnpaidPatients_SelectionChanged(object sender, EventArgs e)
        {
            if (dataGridViewUnpaidPatients.SelectedRows.Count > 0)
            {
                var selectedRow = dataGridViewUnpaidPatients.SelectedRows[0];
                var patientInfo = selectedRow.DataBoundItem as PatientInfo;
                if (patientInfo != null)
                {
                    LoadPatientInfo(patientInfo);
                    LoadMedicines(patientInfo.PatientId);
                }
            }
        }

        /// <summary>
        /// 支付金额文本变更事件
        /// </summary>
        private void TextBoxPayAmount_TextChanged(object sender, EventArgs e)
        {
            CalculateChange();
        }

        /// <summary>
        /// 窗体加载事件
        /// </summary>
        private void OutpatientChargeForm_Load(object sender, EventArgs e)
        {
            InitializeDataGridViews();
            LoadUnpaidPatients();
        }

        /// <summary>
        /// 门诊结账按钮点击事件
        /// </summary>
        private void ButtonCheckout_Click(object sender, EventArgs e)
        {
            try
            {
                // 验证是否选择了患者
                if (dataGridViewUnpaidPatients.SelectedRows.Count == 0)
                {
                    MessageBox.Show("请先选择要结账的患者", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 验证支付金额
                if (string.IsNullOrEmpty(textBoxPayAmount.Text))
                {
                    MessageBox.Show("请输入支付金额", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (!decimal.TryParse(textBoxPayAmount.Text, out decimal payAmount))
                {
                    MessageBox.Show("支付金额格式不正确", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (!decimal.TryParse(textBoxTotalAmount.Text, out decimal totalAmount))
                {
                    MessageBox.Show("总金额格式不正确", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (payAmount < totalAmount)
                {
                    MessageBox.Show("支付金额不足", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 获取选中的患者信息
                var selectedRow = dataGridViewUnpaidPatients.SelectedRows[0];
                var patientInfo = selectedRow.DataBoundItem as PatientInfo;
                if (patientInfo != null)
                {
                    // 执行收费处理
                    ProcessChargeAsync(patientInfo.PatientId);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"结账失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        #region 业务方法
        /// <summary>
        /// 加载未付费患者列表
        /// </summary>
        private async void LoadUnpaidPatients()
        {
            try
            {
                string url = $"{API_BASE_URL}/api/Medical/GetUnpaidPatients";
                var response = await _httpClient.GetAsync(url);
                
                if (response.IsSuccessStatusCode)
                {
                    string jsonContent = await response.Content.ReadAsStringAsync();
                    var apiResult = JsonConvert.DeserializeObject<APIResult<List<PatientInfo>>>(jsonContent);
                    
                    if (apiResult.Code == 200 && apiResult.Data != null) // 修复API返回码检查，APIEnums.Success = 200
                    {
                        dataGridViewUnpaidPatients.DataSource = apiResult.Data;
                    }
                    else
                    {
                        MessageBox.Show(apiResult.Msg ?? "获取未付费患者列表失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    MessageBox.Show($"获取未付费患者列表失败：{response.StatusCode}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载未付费患者列表失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 搜索患者信息
        /// </summary>
        /// <param name="registrationNumber">挂单号</param>
        /// <param name="patientName">患者姓名</param>
        /// <param name="gender">性别</param>
        private async void SearchPatients(string registrationNumber, string patientName, string gender)
        {
            try
            {
                var queryParams = new List<string>();
                if (!string.IsNullOrEmpty(registrationNumber))
                    queryParams.Add($"registrationNo={registrationNumber}");
                if (!string.IsNullOrEmpty(patientName))
                    queryParams.Add($"patientName={patientName}");
                if (!string.IsNullOrEmpty(gender))
                    queryParams.Add($"gender={gender}");

                string queryString = string.Join("&", queryParams);
                string url = $"{API_BASE_URL}/api/Medical/GetUnpaidPatients?{queryString}";

                var response = await _httpClient.GetAsync(url);
                if (response.IsSuccessStatusCode)
                {
                    string jsonContent = await response.Content.ReadAsStringAsync();
                    var apiResult = JsonConvert.DeserializeObject<APIResult<List<PatientInfo>>>(jsonContent);
                    
                    if (apiResult.Code == 200 && apiResult.Data != null) // 修复API返回码检查，APIEnums.Success = 200
                    {
                        dataGridViewUnpaidPatients.DataSource = apiResult.Data;
                        
                        if (apiResult.Data.Count == 0)
                        {
                            MessageBox.Show("未找到符合条件的患者", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                    else
                    {
                        MessageBox.Show(apiResult.Msg ?? "查询失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    MessageBox.Show($"查询失败：{response.StatusCode}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"查询异常：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 加载患者信息到上方表单
        /// </summary>
        /// <param name="patientInfo">患者信息</param>
        private void LoadPatientInfo(PatientInfo patientInfo)
        {
            textBoxRegistrationNumber.Text = patientInfo.RegistrationNumber;
            textBoxDoctor.Text = patientInfo.Doctor;
            comboBoxDepartment.Text = patientInfo.Department;
            textBoxPatientName.Text = patientInfo.Name;
            textBoxIdCard.Text = patientInfo.IdCard;
            comboBoxGender.Text = patientInfo.Gender;
        }

        /// <summary>
        /// 加载患者药品信息
        /// </summary>
        /// <param name="patientId">患者ID</param>
        /// <param name="registrationNo">挂单号（可选）</param>
        private async void LoadMedicines(string patientId, string? registrationNo = null)
        {
            try
            {
                string url = $"{API_BASE_URL}/api/Medical/GetPatientMedicines?patientId={patientId}";
                if (!string.IsNullOrEmpty(registrationNo))
                {
                    url += $"&registrationNo={registrationNo}";
                }
                
                var response = await _httpClient.GetAsync(url);
                
                if (response.IsSuccessStatusCode)
                {
                    string jsonContent = await response.Content.ReadAsStringAsync();
                    var apiResult = JsonConvert.DeserializeObject<APIResult<List<MedicineChargeInfo>>>(jsonContent);
                    
                    if (apiResult.Code == 200 && apiResult.Data != null) // 修复API返回码检查，APIEnums.Success = 200
                    {
                        dataGridViewPatientDetails.DataSource = apiResult.Data;
                        CalculateTotalAmount(apiResult.Data);
                    }
                    else
                    {
                        dataGridViewPatientDetails.DataSource = null;
                        textBoxTotalAmount.Text = "0.00";
                        MessageBox.Show(apiResult.Msg ?? "获取患者药品信息失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    dataGridViewPatientDetails.DataSource = null;
                    textBoxTotalAmount.Text = "0.00";
                    MessageBox.Show($"获取患者药品信息失败：{response.StatusCode}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载药品信息异常：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                dataGridViewPatientDetails.DataSource = null;
                textBoxTotalAmount.Text = "0.00";
            }
        }

        /// <summary>
        /// 计算总金额
        /// </summary>
        /// <param name="medicines">药品列表</param>
        private void CalculateTotalAmount(List<MedicineChargeInfo> medicines)
        {
            // 直接使用API返回的Amount字段，而不是重新计算UnitPrice * Quantity
            decimal totalAmount = medicines?.Sum(m => m.Amount) ?? 0;
            textBoxTotalAmount.Text = totalAmount.ToString("F2");
        }

        /// <summary>
        /// 计算找零
        /// </summary>
        private void CalculateChange()
        {
            if (decimal.TryParse(textBoxTotalAmount.Text, out decimal totalAmount) &&
                decimal.TryParse(textBoxPayAmount.Text, out decimal payAmount))
            {
                decimal change = payAmount - totalAmount;
                textBoxChange.Text = change >= 0 ? change.ToString("F2") : "0.00";
            }
            else
            {
                textBoxChange.Text = "0.00";
            }
        }

        /// <summary>
        /// 处理收费
        /// </summary>
        /// <param name="patientId">患者ID</param>
        private async Task ProcessChargeAsync(string patientId)
        {
            try
            {
                var chargeItems = GetChargeItems();
                if (chargeItems.Count == 0)
                {
                    MessageBox.Show("没有收费项目", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                decimal totalAmount = GetTotalAmount();
                decimal paidAmount = GetPaidAmount();
                decimal changeAmount = paidAmount - totalAmount;
                
                var chargeRequest = new
                {
                    PatientId = long.Parse(patientId), // 转换为long类型
                    RegistrationNo = textBoxRegistrationNumber.Text.Trim(), // 添加挂单号
                    TotalAmount = totalAmount,
                    PaidAmount = paidAmount, // 添加实付金额
                    ChangeAmount = changeAmount, // 添加找零金额
                    ChargeItems = chargeItems,
                    ChargeTime = DateTime.Now,
                    Cashier = "系统用户", // 添加收费员
                    PaymentMethod = "现金" // 添加支付方式
                };

                string jsonContent = JsonConvert.SerializeObject(chargeRequest);
                var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
                
                string url = $"{WRITE_API_BASE_URL}/api/Medical/CreateCharge";
                var response = await _httpClient.PostAsync(url, content);
                
                if (response.IsSuccessStatusCode)
                {
                    string responseContent = await response.Content.ReadAsStringAsync();
                    var apiResult = JsonConvert.DeserializeObject<APIResult<string>>(responseContent);
                    
                    if (apiResult.Code == 200) // 修复API返回码检查，APIEnums.Success = 200
                    {
                        MessageBox.Show("收费成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        ClearForm();
                        LoadUnpaidPatients();
                    }
                    else
                    {
                        MessageBox.Show(apiResult.Msg ?? "收费失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    MessageBox.Show($"收费失败：{response.StatusCode}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"收费异常：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 获取收费项目
        /// </summary>
        /// <returns>收费项目列表</returns>
        private List<object> GetChargeItems()
        {
            var chargeItems = new List<object>();
            if (dataGridViewPatientDetails.DataSource is List<MedicineChargeInfo> medicines)
            {
                foreach (var medicine in medicines)
                {
                    chargeItems.Add(new
                    {
                        MedicineId = medicine.MedicineId, // 添加药品ID
                        MedicineName = medicine.MedicineName,
                        Quantity = medicine.Quantity,
                        UnitPrice = medicine.UnitPrice,
                        Amount = medicine.Amount,
                        PrescriptionId = "" // 添加处方ID，暂时为空
                    });
                }
            }
            return chargeItems;
        }

        /// <summary>
        /// 获取总金额
        /// </summary>
        /// <returns>总金额</returns>
        private decimal GetTotalAmount()
        {
            if (decimal.TryParse(textBoxTotalAmount.Text, out decimal amount))
            {
                return amount;
            }
            return 0;
        }

        /// <summary>
        /// 获取支付金额
        /// </summary>
        /// <returns>支付金额</returns>
        private decimal GetPaidAmount()
        {
            if (decimal.TryParse(textBoxPayAmount.Text, out decimal amount))
            {
                return amount;
            }
            return 0;
        }

        /// <summary>
        /// 清空表单
        /// </summary>
        private void ClearForm()
        {
            textBoxRegistrationNumber.Clear();
            textBoxDoctor.Clear();
            comboBoxDepartment.SelectedIndex = -1;
            textBoxPatientName.Clear();
            textBoxIdCard.Clear();
            comboBoxGender.SelectedIndex = -1;
            textBoxTotalAmount.Text = "0.00";
            textBoxPayAmount.Clear();
            textBoxChange.Text = "0.00";
            dataGridViewUnpaidPatients.ClearSelection();
            dataGridViewPatientDetails.DataSource = null;
        }
        #endregion

        #region 资源释放
        /// <summary>
        /// 释放HTTP客户端资源
        /// </summary>
        private void DisposeHttpClient()
        {
            _httpClient?.Dispose();
        }
        #endregion
    }

    #region 数据模型类
    /// <summary>
    /// 患者信息类
    /// </summary>
    public class PatientInfo
    {
        public string PatientId { get; set; } = string.Empty;
        public string RegistrationNumber { get; set; } = string.Empty;
        public string Name { get; set; } = string.Empty;
        public string Gender { get; set; } = string.Empty;
        public string Age { get; set; } = string.Empty;
        public string IdCard { get; set; } = string.Empty;
        public string Doctor { get; set; } = string.Empty;
        public string Department { get; set; } = string.Empty;
        public string Phone { get; set; } = string.Empty;
        public string Address { get; set; } = string.Empty;
    }

    /// <summary>
    /// 药品收费信息类
    /// </summary>
    public class MedicineChargeInfo
    {
        public string MedicineId { get; set; } = string.Empty;
        public string MedicineName { get; set; } = string.Empty;
        public string Specification { get; set; } = string.Empty;
        public int Quantity { get; set; }
        public decimal UnitPrice { get; set; }
        public decimal Amount { get; set; }
    }

    /// <summary>
    /// API返回结果类
    /// </summary>
    public class APIResult<T>
    {
        public int Code { get; set; }
        public string Msg { get; set; }
        public T Data { get; set; }
    }
    #endregion
}